#include "alta.h"

void board_init(void){
    //需要切换HSI模式
    SYS_SwitchHSIClock();
    SYS_EnableAHBClock(AHB_MASK_DMAC0);
    PERIPHERAL_ENABLE(DMAC, 0);
    DMAC_Init();

    SYS_EnableAPBClock(APB_MASK_FCB0);

    if(!FCB_IsInit()){
        //FCB_EnableInt(1);
    }
    if(!FCB_IsActive()){
        FCB_DeActivate();
    }

    uint32_t v1 = *(uint32_t*)0x81000030;
    uint32_t v2 = *(uint32_t*)0x81000034;
    if(v1+v2!=0xffffffff){
        v1 = *(uint32_t*)0x81000038;
        v2 = *(uint32_t*)0x8100003c;
    }

    // FLASH_Unlock();
    // FLASH_EraseChip();
    // FLASH_Lock();

    //FCB_err = FCB_AutoDecompress(0X80036b00);
    int FCB_err = FCB_AutoDecompress(v1);

    SYS_SetPLLFreq(100*1000*1000);

    SYS_SwitchPLLClock(0);

    INT_Init();
    INT_EnableIntGlobal();
    INT_EnableIntExternal();
}

typedef struct load_data_t{
  uint8_t*  data;
  uint8_t*  end_data;
  int      (*update)(struct load_data_t*);
}load_data_t;

extern int FCB_AutoDecompressData(load_data_t*d);

void board_load_fpga(load_data_t*dd){
    //关闭所有中断
    INT_DisableIntExternal();
    INT_DisableIntGlobal();
    INT_Init();
    //需要切换成HSI模式
    SYS_SwitchHSIClock();
    SYS_EnableAHBClock(AHB_MASK_DMAC0);
    PERIPHERAL_ENABLE(DMAC, 0);
    DMAC_Init();

    SYS_EnableAPBClock(APB_MASK_FCB0);
    if(!FCB_IsActive()){
        FCB_Activate();
    }

    int FCB_err = FCB_AutoDecompress(dd->data);
    SYS_SetPLLFreq(100*1000*1000);
    SYS_SwitchPLLClock(0);
    INT_EnableIntGlobal();
    INT_EnableIntExternal();
}

